package com.siblings.loan.sys.data.http

import com.siblings.loan.sys.data.ASSycBuilder
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.function.Supplier

class ASPostAsyncTask(val url: String, val body: String, val taskId: String? = null) :
    Supplier<JSONObject> {

    override fun get(): JSONObject {
        return ASPostSyncTask(url = url, body = body, taskId = taskId).doPost()
    }
}

class ASPostSyncTask(val url: String, val body: String, val taskId: String? = null) {

    fun doPost(): JSONObject {
        try {
            if (this.url.isBlank() or this.body.isBlank()) return JSONObject().apply {
                put("taskId", taskId)
            }

            httpURLConnection(this.url).apply {
                outputStream.write(body.toByteArray())
                outputStream.flush()
                outputStream.close()

                val isSuccess = (responseCode == HttpURLConnection.HTTP_OK)
                disconnect()

                if (isSuccess) {
                    return JSONObject().apply {
                        put("taskId", taskId)
                    }
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return JSONObject().apply {
            put("taskId", taskId)
        }
    }

    @Throws(IOException::class)
    private fun httpURLConnection(toUrl: String): HttpURLConnection {
        val url = URL(toUrl)
        val urlConnection = url.openConnection() as HttpURLConnection
        urlConnection.setDoInput(true)
        urlConnection.setDoOutput(true)
        urlConnection.setUseCaches(false)
        urlConnection.setReadTimeout(180000)
        urlConnection.setConnectTimeout(120000)
        urlConnection.setRequestMethod("POST")
        urlConnection.setRequestProperty("Charset", "UTF-8")
        urlConnection.setRequestProperty("Connection", "Keep-Alive")
        urlConnection.setRequestProperty("Content-Type", "text/plain")
        urlConnection.setRequestProperty("Accept", "*/*")
        urlConnection.setRequestProperty("product", ASSycBuilder.product)
        urlConnection.setRequestProperty("appid", ASSycBuilder.product)
        return urlConnection
    }
}